package com.hy.chat.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.hy.chat.client.ChatService;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class ChatServiceImpl extends RemoteServiceServlet implements
		ChatService {

	Map<String, ArrayList<String>> messageListContianer = new HashMap<String, ArrayList<String>>();
	LinkedList<String> indexList = new LinkedList<String>();
	public static final int MAX_SESSIONS = 2;
	
	public String greetServer(String input) throws IllegalArgumentException {
	

		System.out.println("**********************************");
		System.out.println("Rpc has already proceeded .");
		System.out.println("**********************************");
		ArrayList<String> messageList = new ArrayList<String>();
		messageList.add(input);
		StringBuffer retunStringBuffer = new StringBuffer();
		
		return input ;
	}

	@Override
	public BaseModel getIndexAndMessage(BaseModel indexAndMessage)
			throws IllegalArgumentException {
		
		ArrayList<String> messageList =null;
		//获取sessionId或者为新seesion获取uuid，并建立messageList结构
		String sessionId = indexAndMessage.get("sessionId");
		if (!this.validateIndexAndMessage(indexAndMessage)) {
			return null;
		}
		if (sessionId == null ||sessionId =="") {
			sessionId = UUID.randomUUID().toString();
			messageList = new ArrayList<String>();
			this.optimizeMessageListContianer(sessionId);
			messageListContianer.put(sessionId, messageList);
			indexList.add(sessionId);
		} 
		
		//为messageList添加新message
		messageList = messageListContianer.get(sessionId);
		//处理过期会话
		if (messageList==null) {
			BaseModel returnBaseModel = new BaseModel();
//			returnBaseModel.set("index", messageList.size());
			returnBaseModel.set("index", 0);
			returnBaseModel.set("message", "对不起，由于长时间未发送信息，您的会话已经过期，请重新打新窗口！<br>");
			returnBaseModel.set("sessionId", sessionId);
			return returnBaseModel ;
		} 
		if (indexAndMessage.get("message")!=null) {
			String ip = this.getThreadLocalRequest().getRemoteAddr();

			messageList.add(ip + " " +((String)indexAndMessage.get("message")));
			
		}
		
		int index = 0;
		StringBuffer retunStringBuffer = new StringBuffer();
		if (indexAndMessage.get("index")!=null) {
			index = ((Integer)indexAndMessage.get("index"));

		}
		int count =0;
		for ( int i = index; i < messageList.size(); i++) {
		
			if (retunStringBuffer.length()==0) {
				retunStringBuffer.append(messageList.get(i));
			} else {

				retunStringBuffer.append("<br>"+messageList.get(i));
			}
			count = count +1;
			
		}
		String returnString = retunStringBuffer.toString();
		BaseModel returnBaseModel = new BaseModel();
//		returnBaseModel.set("index", messageList.size());
		returnBaseModel.set("index", index + count);
		returnBaseModel.set("message", returnString);
		returnBaseModel.set("sessionId", sessionId);
		return returnBaseModel ;

	}

	
	@Override
	public List<BaseModel> getAdminIndexAndMessage(List<BaseModel> indexAndMessageList)
			throws IllegalArgumentException {
		List<BaseModel> list = new ArrayList<BaseModel>();
		//ArrayList<String> messageList =null;
		/*for (BaseModel baseModel : indexAndMessageList) {
					
					list.add(this.getIndexAndMessage(baseModel));
				}*/
		
		for (String key : messageListContianer.keySet()) {
			BaseModel findResult = findIndexAndMessage(key, indexAndMessageList);
			if (findResult==null) {
				BaseModel temp = new BaseModel();
				temp.set("sessionId", key);
				temp.set("message", null);
				temp.set("index", 0);
				list.add(this.getIndexAndMessage(temp));
			}else {
				list.add(this.getIndexAndMessage(findResult));

			}
		}
		
		/*for (BaseModel baseModel : indexAndMessageList) {
			
			list.add(this.getIndexAndMessage(baseModel));
		}*/
		
		return list ;

	}
	
	private BaseModel findIndexAndMessage(String sessionId,List<BaseModel> messageList) {
		
		
		if (sessionId == null ||sessionId =="") {
			return null;
		} 
		for (BaseModel baseModel : messageList) {
			if(sessionId.equals(baseModel.get("sessionId"))){
				return baseModel;
			}
		}
		return null;
	}
	
	
	/**
	 * 
	 * @param sessionId
	 */
	private void optimizeMessageListContianer(String sessionId) {
		
		if (messageListContianer.keySet().size()<MAX_SESSIONS) {
			return ;
		}
		
		for (String key : messageListContianer.keySet()) {
			
			if (key.equals(sessionId)) {
				return;
			}else {
				//TODO 易错
			}
		}
		
		messageListContianer.remove(indexList.get(0));

		indexList.remove(0);
	}
	
	private Boolean validateIndexAndMessage(BaseModel indexAndMessage) {
		String sessionId = indexAndMessage.get("sessionId");
		if ((sessionId == null ||sessionId =="")&&(Integer)(indexAndMessage.get("index"))==0&&(indexAndMessage.get("message")==null||"".equals(indexAndMessage.get("message")))) {
			System.err.println("这是一次非法访问：getIndexAndMessage");
			return false;
		}
		return true;
	}
	
}
